<!--
 * @Description: 投入成本管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">投入类型:</div>
          <div class="input">
            <el-select
              v-model="searchList.queryOwn"
              placeholder="请选择"
              clearable
              filterable
            >
              <el-option
                v-for="item in queryOwnList"
                :key="item.index"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>
        </div>
        <div class="common-search-item">
          <div class="label">名称:</div>
          <div class="input">
            <el-input
              v-model="searchList.inputName"
              placeholder="请输入名称"
              clearable
            />
          </div>
        </div>
        <div class="common-search-item">
          <div class="label">时间选择:</div>
          <div class="input">
            <StartTimeEndTimeSelectionBox @startVal="startVal" @endVal="endVal" />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="ownName" label="类型" width="160" />
        <el-table-column prop="inputName" label="名称" min-width="120" />
        <el-table-column prop="specification" label="规格">
          <template slot-scope="scope">
            {{ scope.row.specification }} {{ scope.row.unitName }}
            <span v-if="scope.row.perSpecUnitName">/  {{ scope.row.perSpecUnitName }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="number" label="数量" /> -->

        <el-table-column prop="number" label="数量">
          <template slot-scope="scope">
            {{ scope.row.number }}
            {{ scope.row.perSpecUnitName }}
          </template>
        </el-table-column>

        <el-table-column prop="price" label="单价">
          <template v-if="scope.row.price" slot-scope="scope">
            {{ scope.row.price }}元

            <span v-if="scope.row.perSpecUnitName">
              /
              {{ scope.row.perSpecUnitName }}
            </span>

          </template>
        </el-table-column>
        <el-table-column prop="total" label="总价">
          <template v-if="scope.row.total" slot-scope="scope">
            <span> {{ scope.row.total }}元 </span>
          </template>
        </el-table-column>
        <el-table-column prop="pictureId" label="投入凭证">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.inputCostId"
              type="text"
              size="small"
              @click="pic(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template v-if="scope.row.inputCostId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="handleEdit(scope.row)"><i class="el-icon-edit-outline"></i> 修改</el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>

    <template v-slot:dialog>

      <el-dialog :title="dialogTitle + '投入成本信息'" :visible.sync="dialogFormVisible" :before-close="cancel">
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="投入名称:" prop="inputName" class="w100p">
            <el-select
              v-model="formData.inputName"
              placeholder="请选择"
              :disabled="formData.ownName !== '订单投入类型' ? !canInput : ''"
              clearable
              filterable
            >
              <el-option
                v-for="item in inputTypeList"
                :key="item.inputTypeId"
                :label="item.typeName"
                :value="item.typeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规格:" prop="specification" style="width:45%;">
            <el-input
              v-model="formData.specification"
              placeholder="请输入规格"
              :disabled="formData.ownName !== '订单投入类型' ? !canInput : ''"
              clearable
            />
          </el-form-item>
          <el-form-item label="单位:" prop="unitId" style="width:55%;">

            <el-form-item prop="unitId" style="width:50%;">
              <el-select
                v-model="formData.unitId"
                :disabled="formData.ownName !== '订单投入类型' ? !canInput : ''"
                clearable
                filterable
              >
                <el-option
                  v-for="item in UnitData"
                  :key="item.unitId"
                  :label="item.unitName"
                  :value="item.unitId"
                />
              </el-select>
            </el-form-item>

            <div style="padding:0 5px">
              /
            </div>
            <el-form-item prop="perSpecUnitId" style="width:50%;">

              <el-select
                v-model="formData.perSpecUnitId"
                style="width:100%;"
                :disabled="formData.ownName !== '订单投入类型' ? !canInput : ''"
                filterable
                clearable
              >
                <el-option
                  v-for="item in UnitData"
                  :key="item.unitId"
                  :label="item.unitName"
                  :value="item.unitId"
                />
              </el-select>
            </el-form-item>

          </el-form-item>
          <el-form-item label="数量:" prop="number" class="w100p">
            <el-input
              v-model="formData.number"
              placeholder="请输入数量"

              clearable
            />
          </el-form-item>
          <el-form-item label="投入单价:" prop="price" class="w100p">
            <el-input
              v-model="formData.price"
              placeholder="请输入投入单价"

              clearable
            />
          </el-form-item>
          <el-form-item label="投入总价:" prop="total" class="w100p">
            <el-input
              v-model="formData.total"
              placeholder="总价 = 数量 * 单价"
              disabled
              clearable
            />
          </el-form-item>
          <el-form-item label="投入时间:" prop="recordDate" class="w100p">
            <el-date-picker
              v-model="formData.recordDate"
              type="datetime"
              placeholder="请选择投入时间"

              value-format="timestamp"
              clearable
            />
          </el-form-item>
          <el-form-item label="备注:" class="w100p">
            <el-input
              v-model="formData.remark"
              placeholder="请输入备注(选填)"

              clearable
            />
          </el-form-item>
          <!-- <el-form-item v-show="!canInput" label="上传凭证" class="w100p imagesty">
            <uploadimage @child-event="getimageurl" />
          </el-form-item> -->
          <el-form-item label="投入凭证:">
            <!-- <div class="mview">
              <i
                v-show="imageurl.length === 0"
                class="el-icon-upload2"
                style="font-size:34px;color:#6ecae3;"
              ></i>
              <img :src="imageurl" style="width: 4px; height: 1.8px" />
            </div> -->
            <ele-upload-image
              v-model="image"
              multiple
              :headers="headers"
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :action="ImageUrl()"
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        class="dialog"
        title="查看凭证"
        :visible.sync="dialogPicFormsVisible"
      >
        <img :src="image" />
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import costManage from "@/api/digital-operation/input-output-management/cost-manage";
import basicInfoManage from "@/api/basic-info-manage/input-type-manage/index";
import unitInfoManage from "@/api/basic-info-manage/unit-manage/index";
import collectionPicture from "@/api/digital-production/collectionPicture/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixin";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
import { getToken } from "@/utils/auth";
import SearchBox from "@/components/SearchBox";
export default {
  name: 'CostManage',
  components: { ActionBar, Pagination, BaseMainSlot, StartTimeEndTimeSelectionBox, SearchBox },
  mixins: [mymixin],
  getToken: [getToken],
  data() {
    return {
      obj: {
        name: ""
      },
      image: "",
      logoImg: require("@/assets/logo.png"),
      // ----上传图片相关---
      // 图片地址
      imageurl: "",
      // ---end---
      searchList: {
        queryOwn: "", // 投入类型
        inputName: "", // 名称
        startTime: "",
        endTime: "" // 投入时间
      },
      // 投入名称列表
      inputTypeList: [],
      // 投入类型列表
      queryOwnList: [],
      // 设施名称
      installationName: "",
      // 选中的设施id数组 ID组成
      inputCostIdList: [],
      UnitData: [],
      own: "",
      pictureId: "",
      startTime: "",
      endTime: "",
      dialogPicFormsVisible: false,
      rules: {
        inputName: [
          {
            required: true,
            message: "请选择投入名称",
            trigger: "change"
          }
        ],
        specification: [
          {
            required: true,
            message: "请输入规格",
            trigger: "blur"
          },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        unitId: [
          {
            required: true,
            message: "请选择单位",
            trigger: "change"
          }
        ],
        perSpecUnitId: [
          {
            required: true,
            message: "请选择单位",
            trigger: "change"
          }
        ],
        number: [
          {
            required: true,
            message: "请输入数量",
            trigger: "blur"
          },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            message: "请输入单价",
            trigger: "blur"
          },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        recordDate: [
          {
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false
    };
  },
  watch: {
    formData: {
      handler(val) {
        // 判断input值改变时才触发
        if (val.price && val.number) {
          // 当input值改变时计算
          this.$set(
            val,
            "total",
            (parseFloat(val.price) * parseFloat(val.number)).toFixed(2)
          );
        }
      },
      deep: true
    }
  },
  created() {
    this.queryDataList();
  },
  mounted() {
    // 获取表格数据
    this.getTableDataList();
  },
  methods: {
    getTableDataList() {
      this.formData = {};
      this.loading = false;
      let params = {
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        own: this.own,
        startTime: this.startTime,
        endTime: this.endTime,
        inputName: this.searchList.inputName
      };
      costManage.seachInfo(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.$refs.formData.resetFields();
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    async queryDataList() {
      // 单位
      const { data: UnitList } = await unitInfoManage.getUnitListByCondition(
        { unitTypeId: 1 }
      )
      this.UnitData = UnitList
      // 投入类型
      const { data: own } = await costManage.getqueryOwn()
      this.queryOwnList = own;
      // 投入名称
      const { data: Tree } = await basicInfoManage.getTreeQueryByCondition()
      this.inputTypeList = Tree;
    },
    // 上传图片
    ImageUrl() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let URL = `${this.basicUrl}addPicture`;
        return URL;
      } else {
        let URL = "#";
        return URL;
      }
    },
    handleResponse(response, file, fileList) {
      // 根据响应结果, 设置 URL
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        this.pictureId = response.data;
        collectionPicture.getColectPicture(this.pictureId).then(res => {
          this.image = "data:image/png;base64," + res.data;
        });
        return this.image;
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    handleRemove() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        collectionPicture.delCollectionPicture(this.pictureId).then(res => {
          if (res.code === 1) {
            this.pictureId = "";
            delete this.formData.pictureId;
            delete this.formData.picture;
            this.$message.success(res.msg);
          }
        });
      } else {
        return this.$message.warning("请点击修改按钮!");
      }
      // console.log(response);
    },
    selectable(row, index) {
      // console.log(row)
      // if (row.status === true) {
      //   this.$message.warning('1')
      // }
      return row.own === 0 // 通过某个值来进行判断，规定那一行的选择框被禁用
    },
    pic(row) {
      if (row.pictureId) {
        this.dialogPicFormsVisible = true;
      } else {
        this.$message.warning('暂无凭证！')
      }
    },
    // 搜索框时间
    startVal(e) {
      this.startTime = e
    },
    endVal(e) {
      this.endTime = e
    },
    search() {
      this.currentPage = 1;
      if (this.searchList.queryOwn === "订单投入类型") {
        this.own = 1;
      } else if (this.searchList.queryOwn === "自行投入类型") {
        this.own = 0;
      } else if (this.searchList.queryOwn === "退货订单投入类型") {
        this.own = 2;
      } else {
        this.own = "";
      }
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },

    add() {
      this.canInput = true;
      this.formData = {};
      this.openDialog('add');
    },
    cancel() {
      this.nowChanceStau = "";
      this.formData = {};
      this.closeDialog();
    },
    handleEdit(row) {
      // console.log(row)
      if (!row.own) {
        // TODO 点击行元素后 edit
        this.formData = JSON.parse(JSON.stringify(row));
        // console.log(this.formData);
        this.pictureId = this.formData.pictureId;
        // console.log(this.pictureId);
        if (this.pictureId !== undefined) {
          collectionPicture.getColectPicture(this.pictureId).then(res => {
            this.image = "data:image/png;base64," + res.data;
          });
        } else {
          this.image = "";
        }
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
        this.canInput = false;
      } else {
        // TODO 点击行元素后 edit
        this.formData = JSON.parse(JSON.stringify(row));
        // console.log(this.formData);
        this.pictureId = this.formData.pictureId;
        // console.log(this.pictureId);
        if (this.pictureId !== undefined) {
          collectionPicture.getColectPicture(this.pictureId).then(res => {
            this.image = "data:image/png;base64," + res.data;
          });
        } else {
          this.image = "";
        }
        this.editActive = false;
        this.saveActive = false;
        this.cancelActive = true;
        this.canInput = false;
        this.openDialog('edit');
      }
      this.$refs.formData.resetFields();
    },
    handleSelectionChange(list) {
      this.inputCostIdList = [];
      this.inputCostIdList = list.map(item => item.inputCostId);
      // console.log(this.inputCostIdList);
      if (this.inputCostIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      costManage.delPageList(this.inputCostIdList).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getTableDataList();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      });
    },
    handleDelete(row) {
      costManage.delPageList([row.inputCostId]).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getTableDataList();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // this.formData.picture = this.pictureId;
            if (this.pictureId) this.formData.picture = this.pictureId;
            // console.log(this.formData);
            costManage.editPageList(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.formData = {};
                this.closeDialog();
                this.$refs[formData].resetFields()
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            this.formData.organizationNo = sessionStorage.organizationNo;
            if (this.pictureId) this.formData.picture = this.pictureId;
            costManage.addPageList(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.formData = {};
                this.closeDialog();
                this.$refs[formData].resetFields()
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === 'add' ? '新增' : '编辑'
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = '';
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
// 图片上传相关
.imagesty .el-upload .el-upload-list--picture-card .el-upload-list__item {
  background-color: #b61b1b !important;
  border: 1px solid #225da1;
}
.el-upload--picture-card {
  background-color: #145da7 !important;
}
// end
::v-deep .el-form-item__content {
  display: flex;
  align-items: center;
}
::v-deep .el-form-item__label {
  min-width: 100px !important;
  text-align: right;
}
::v-deep .label {
  text-align: end;
  padding: 0 10px;
}
.dialog {
  ::v-deep .el-dialog__title {
    font-weight: bold;
  }
  .qrCode {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.tags {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .tag-item {
    height: 30px;
    padding: 5px 10px;
    background-color: #00a1c2;
    border-radius: 8px;
    display: flex;
    align-items: center;
    margin-top: 10px;
    margin-right: 10px;
    i {
      font-size: 14px;
    }
  }
}

::v-deep .el-upload--picture-card {
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #6ecae3;
}
::v-deep .el-upload--picture-card {
  position: relative;
  .el-loading-parent--relative {
    position: absolute !important;
  }
  .el-loading-spinner {
    top: 13%;
    width: 1%;
  }
}
::v-deep .el-upload--picture-card .el-icon-plus {
  font-size: 34px;
  color: #6ecae3;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
::v-deep .el-dialog__body {
  height: 90%;
  text-align: center;
  img {
    width: 100%;
  }
}
</style>
